/*
 * @Descripttion: 
 * @version: 
 * @Author: 
 * @Date: 2022-04-25 11:40:02
 * @LastEditors: weidelong weidelong@szkingdom.com
 * @LastEditTime: 2022-05-17 18:48:13
 */
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.send('<h1>这是一个socket服务</h1>');
});

 // 用于接收在线人数，保证人数是最新的，传给前端
let userList = [
//   {
//     name: '默认群聊',
//     img: ''
//   }
]

io.on('connection', function(socket) {
  console.log('有一个连接')
  // 监听用户登录事件
  socket.on('login', (data, callback) => {
    let islogin = true
    io.sockets.sockets.forEach(element => {
      if (element.name == data.name) {
        islogin = false
      }
    });
    if (islogin) {
      console.log('用户登录成功', data)
      userList.push(data)
      socket.name = data.name
      callback(true)
      io.emit('login', userList)
    } else {
      console.log('登录失败')
      callback(false)
    }
    })

    // 群聊
    socket.on('groupChat', data => {
      data.type = 'user'
      socket.broadcast.emit('updateChatMessageList', data)
    })

    // 私聊
    socket.on('privateChat', data => {
      /* 根据对象的name，找到对应的私聊对象的cocket.id */
      io.sockets.sockets.forEach( iss => {
        if (iss.name === data.receiver) {
            data.type = 'user'
            console.log(data)
            io.to(iss.id).emit('updateChatMessageList', data)
        }
      })
    })

    // 监听文章提交
    socket.on('submit', data => {
        console.log(data)
        io.emit('articleRemind', data)
    })

    // socket.on('privateUser', data=>{
    //   console.log(data)
    //   /* 根据对象的name，找到对应的私聊对象的cocket.id */
    //   io.sockets.sockets.forEach( iss => {
    //     if (iss.name === data.username) {
    //         io.to(iss.id).emit('fromDoctor', {
    //           type: 'user',
    //           time: data.time,
    //           content: data.data
    //         })
    //     }
    //   })
    // })

    /*用户掉线 */
    socket.on('disconnect', () => {
        userList = userList.filter(i => i.name !== socket.name)
        io.emit('login', userList)
        io.emit('outLine', {a: Math.random()})
        console.log(socket.name+'离线')
    })

})
 
http.listen(3001, function(){
  console.log('listening on *:3001');
});